<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/userStore';
import { useSnackbarStore } from '@/store/snackbarStore';
import { updateProfile } from '@/api/user';

const userStore = useUserStore();
const snackbarStore = useSnackbarStore();

// 表单数据
const formData = reactive({
  id: null as number | null,
  username: '',
  name: '',
  phone: '',
  gender: '',
  role: '',
  is_active: true,
  extra_info: ''
});

// 额外信息表单
const extraInfoForm = reactive({
  department: '',
  class: '',
  title: '',
  specialty: '',
  qualification: '',
  responsibility: '',
  description: '',
  avatar: ''
});

// 表单验证
const formValid = ref(false);
const loading = ref(false);
const saving = ref(false);

// 计算属性
const currentUser = computed(() => userStore.getCurrentUser);
const roleText = computed(() => userStore.getRoleText);
const genderText = computed(() => userStore.getGenderText);

// 性别选项
const genderOptions = [
  { title: '男', value: 'M' },
  { title: '女', value: 'F' }
];

// 角色选项
const roleOptions = [
  { title: '学生', value: 'STUDENT' },
  { title: '初访员', value: 'INITIAL_VISITOR' },
  { title: '心理助理', value: 'ASSISTANT' },
  { title: '咨询师', value: 'CONSULTANT' },
  { title: '管理员', value: 'ADMIN' }
];

// 表单验证规则
const rules = {
  required: (v: string) => !!v || '此项为必填项'
};

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true;
  try {
    if (userStore.username && !userStore.name) {
      await userStore.getCurrentUserInfo();
    }
    
    const user = userStore.getCurrentUser;
    formData.id = user.id;
    formData.username = user.username;
    formData.name = user.name;
    formData.phone = user.phone;
    formData.gender = user.gender;
    formData.role = user.role;
    formData.is_active = user.is_active;
    formData.extra_info = user.extra_info;
    
    // 解析额外信息
    parseExtraInfo();
  } catch (error) {
    console.error('加载用户信息失败:', error);
    snackbarStore.showMessage('加载用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 解析额外信息
const parseExtraInfo = () => {
  try {
    if (formData.extra_info) {
      const extraInfo = JSON.parse(formData.extra_info);
      extraInfoForm.department = extraInfo.department || '';
      extraInfoForm.class = extraInfo.class || '';
      extraInfoForm.title = extraInfo.title || '';
      extraInfoForm.specialty = extraInfo.specialty || '';
      extraInfoForm.qualification = extraInfo.qualification || '';
      extraInfoForm.responsibility = extraInfo.responsibility || '';
      extraInfoForm.description = extraInfo.description || '';
      extraInfoForm.avatar = extraInfo.avatar || '';
    }
  } catch (error) {
    console.error('解析额外信息失败:', error);
  }
};

// 构建额外信息JSON
const buildExtraInfo = () => {
  const extraInfo: any = {};
  
  if (extraInfoForm.department) extraInfo.department = extraInfoForm.department;
  if (extraInfoForm.class) extraInfo.class = extraInfoForm.class;
  if (extraInfoForm.title) extraInfo.title = extraInfoForm.title;
  if (extraInfoForm.specialty) extraInfo.specialty = extraInfoForm.specialty;
  if (extraInfoForm.qualification) extraInfo.qualification = extraInfoForm.qualification;
  if (extraInfoForm.responsibility) extraInfo.responsibility = extraInfoForm.responsibility;
  if (extraInfoForm.description) extraInfo.description = extraInfoForm.description;
  if (extraInfoForm.avatar) extraInfo.avatar = extraInfoForm.avatar;
  
  return JSON.stringify(extraInfo);
};

// 保存个人资料
const saveProfile = async () => {
  if (!formValid.value) return;
  
  saving.value = true;
  try {
    const profileData = {
      id: formData.id,
      username: formData.username,
      name: formData.name,
      phone: formData.phone,
      gender: formData.gender,
      role: formData.role,
      is_active: formData.is_active,
      extra_info: buildExtraInfo()
    };
    
    const response = await updateProfile(profileData);
    
    if (response.data && response.data.success) {
      // 更新store中的用户信息
      userStore.setUserInfo(response.data.data);
      snackbarStore.showMessage('个人资料更新成功');
    } else {
      snackbarStore.showMessage(response.data?.message || '更新失败');
    }
  } catch (error) {
    console.error('保存个人资料失败:', error);
    snackbarStore.showMessage('保存失败，请重试');
  } finally {
    saving.value = false;
  }
};

// 头像上传
const fileInput = ref<HTMLInputElement>();
const selectImage = () => {
  fileInput.value?.click();
};

const handleImageSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    snackbarStore.showMessage('请选择图片文件');
    return;
  }

  // 验证文件大小 (限制2MB)
  if (file.size > 2 * 1024 * 1024) {
    snackbarStore.showMessage('图片文件大小不能超过2MB');
    return;
  }

  // 读取文件并转换为Base64
  const reader = new FileReader();
  reader.onload = (e) => {
    const base64 = e.target?.result as string;
    extraInfoForm.avatar = base64;
  };
  reader.readAsDataURL(file);
  
  // 清空文件输入
  target.value = '';
};

// 重置表单
const resetForm = () => {
  loadUserInfo();
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserInfo();
});
</script>

<template>
  <section>
    <VRow>
      <VCol cols="12">
        <VCard>
          <VCardTitle class="d-flex align-center">
            <VIcon icon="mdi-account-outline" size="32" color="primary" class="mr-3" />
            <span class="text-h5">个人资料</span>
          </VCardTitle>
          
          <VCardText>
            <VForm v-model="formValid" @submit.prevent="saveProfile">
              <VRow>
                <!-- 基本信息 -->
                <VCol cols="12">
                  <VCard variant="outlined">
                    <VCardTitle class="text-h6">基本信息</VCardTitle>
                    <VCardText>
                      <VRow>
                        <!-- 头像 -->
                        <VCol cols="12" md="4" class="text-center">
                          <VAvatar 
                            size="120" 
                            class="mb-4 cursor-pointer"
                            @click="selectImage"
                          >
                            <VImg 
                              v-if="extraInfoForm.avatar" 
                              :src="extraInfoForm.avatar" 
                              alt="头像" 
                            />
                            <VImg 
                              v-else 
                              src="@/assets/images/users/avatar-1.jpg" 
                              alt="默认头像" 
                            />
                          </VAvatar>
                          <div>
                            <VBtn 
                              size="small" 
                              color="primary" 
                              variant="outlined"
                              @click="selectImage"
                            >
                              更换头像
                            </VBtn>
                          </div>
                        </VCol>
                        
                        <!-- 基本信息表单 -->
                        <VCol cols="12" md="8">
                          <VRow>
                            <VCol cols="12" sm="6">
                              <VTextField
                                v-model="formData.username"
                                label="学号"
                                variant="outlined"
                                readonly
                                prepend-inner-icon="mdi-account"
                                hint="学号不可修改"
                                persistent-hint
                              />
                            </VCol>
                            <VCol cols="12" sm="6">
                              <VTextField
                                v-model="formData.name"
                                label="姓名"
                                variant="outlined"
                                readonly
                                prepend-inner-icon="mdi-account-outline"
                                hint="姓名不可修改"
                                persistent-hint
                              />
                            </VCol>
                            <VCol cols="12" sm="6">
                              <VSelect
                                v-model="formData.gender"
                                :items="genderOptions"
                                label="性别"
                                variant="outlined"
                                readonly
                                prepend-inner-icon="mdi-gender-male-female"
                                hint="性别不可修改"
                                persistent-hint
                              />
                            </VCol>
                            <VCol cols="12" sm="6">
                              <VSelect
                                v-model="formData.role"
                                :items="roleOptions"
                                label="身份角色"
                                variant="outlined"
                                readonly
                                prepend-inner-icon="mdi-account-tie"
                                hint="身份角色不可修改"
                                persistent-hint
                              />
                            </VCol>
                          </VRow>
                        </VCol>
                      </VRow>
                    </VCardText>
                  </VCard>
                </VCol>
                
                <!-- 额外信息 -->
                <VCol cols="12">
                  <VCard variant="outlined">
                    <VCardTitle class="text-h6">详细信息</VCardTitle>
                    <VCardText>
                      <VRow>
                        <!-- 联系电话 -->
                        <VCol cols="12" sm="6">
                          <VTextField
                            v-model="formData.phone"
                            label="联系电话"
                            variant="outlined"
                            :rules="[rules.required]"
                            prepend-inner-icon="mdi-phone"
                            placeholder="请输入联系电话"
                          />
                        </VCol>
                        
                        <!-- 学生信息 -->
                        <template v-if="formData.role === 'STUDENT'">
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.department"
                              label="院系"
                              variant="outlined"
                              prepend-inner-icon="mdi-school"
                              placeholder="请输入院系"
                            />
                          </VCol>
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.class"
                              label="班级"
                              variant="outlined"
                              prepend-inner-icon="mdi-account-group"
                              placeholder="请输入班级"
                            />
                          </VCol>
                        </template>
                        
                        <!-- 教职工信息 -->
                        <template v-else-if="formData.role === 'CONSULTANT' || formData.role === 'INITIAL_VISITOR'">
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.title"
                              label="职称"
                              variant="outlined"
                              prepend-inner-icon="mdi-account-star"
                              placeholder="请输入职称"
                            />
                          </VCol>
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.qualification"
                              label="资格证书"
                              variant="outlined"
                              prepend-inner-icon="mdi-certificate"
                              placeholder="请输入资格证书"
                            />
                          </VCol>
                          <VCol cols="12">
                            <VTextField
                              v-model="extraInfoForm.specialty"
                              label="专业方向"
                              variant="outlined"
                              prepend-inner-icon="mdi-brain"
                              placeholder="请输入专业方向"
                            />
                          </VCol>
                        </template>
                        
                        <!-- 助理信息 -->
                        <template v-else-if="formData.role === 'ASSISTANT'">
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.title"
                              label="职称"
                              variant="outlined"
                              prepend-inner-icon="mdi-account-star"
                              placeholder="请输入职称"
                            />
                          </VCol>
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.responsibility"
                              label="职责"
                              variant="outlined"
                              prepend-inner-icon="mdi-clipboard-list"
                              placeholder="请输入职责"
                            />
                          </VCol>
                        </template>
                        
                        <!-- 管理员信息 -->
                        <template v-else-if="formData.role === 'ADMIN'">
                          <VCol cols="12" sm="6">
                            <VTextField
                              v-model="extraInfoForm.title"
                              label="职称"
                              variant="outlined"
                              prepend-inner-icon="mdi-account-star"
                              placeholder="请输入职称"
                            />
                          </VCol>
                        </template>
                        
                        <!-- 个人简介 -->
                        <VCol cols="12">
                          <VTextarea
                            v-model="extraInfoForm.description"
                            label="个人简介"
                            variant="outlined"
                            rows="3"
                            prepend-inner-icon="mdi-text"
                            placeholder="请输入个人简介..."
                          />
                        </VCol>
                      </VRow>
                    </VCardText>
                  </VCard>
                </VCol>
              </VRow>
            </VForm>
          </VCardText>
          
          <VCardActions>
            <VSpacer />
            <VBtn 
              color="secondary" 
              variant="outlined"
              @click="resetForm"
              :disabled="saving"
            >
              重置
            </VBtn>
            <VBtn 
              color="primary" 
              @click="saveProfile"
              :loading="saving"
              :disabled="!formValid"
            >
              保存
            </VBtn>
          </VCardActions>
        </VCard>
      </VCol>
    </VRow>
    
    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageSelect"
    />
  </section>
</template>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}
</style>
